<?php


namespace app\admin\services;


use app\admin\controller\Bom;
use app\admin\model\BomModel;
use think\facade\Db;
use think\facade\Validate;
use think\Model;

class BomService extends BaseService
{
    /**
     * 递归子树，废弃
     * @param $p
     * @return void
     */
    public static function recursionList($p = [])
    {
        $p = [
            'where' => [],
            'page' => 'all',
            'order' => 'level desc',
            'field' => 'id,parent_id,sku_id',
            'with' => [
                'sku' => function ($query) {
                    return $query->withField(['id', 'label'])->withDefault(['id' => '', 'label' => 'SKU已删除']);
                }
            ]
        ];
        $list = BomModel::getList($p)->toArray();
        $list = array_column($list, null, 'id');
        foreach ($list as $key => $item) {
            $list[$key]['label'] = $item['sku']['label'];
            if (!empty($list[$key]['children'])) {
                $list[$key]['icon'] = 'el-icon-folder';
            } else {
                $list[$key]['icon'] = 'el-icon-document';
            }
            if ($item['parent_id'] && !empty($list[$item['parent_id']])) {
                $list[$item['parent_id']]['children'][] = $list[$key];
                unset($list[$key]);
            }
        }
        api_return(200, '', ['treeData' => array_values($list)]);
    }

    public static function skuRecursionList($p)
    {
        $params = [
            'where' => [],
            'page' => 'all',
            'order' => 'id desc',
            'field' => 'sum(parent_sku_id) as sum_parent,sku_id',
            'with' => [
                'sku' => function ($query) {
                    return $query->withField(['id', 'label'])->withDefault(['id' => '', 'label' => 'SKU已删除']);
                }
            ],
            'group' => 'sku_id'
        ];
        if (!empty($p['sku_id'])) {
            $params['where'][] = ['sku_id', 'in', $p['sku_id']];
        }
        if (!empty($p['parent_sku_id'])) {
            $params['where'][] = ['parent_sku_id', '=', $p['parent_sku_id']];
        } else {
            $params['having'] = 'sum_parent = 0';

        }
        $list = BomModel::getList($params);
        foreach ($list as $item) {
            $item['icon'] = 'el-icon-document';
            $item['label'] = $item->sku['label'];
            $item['expand'] = false;
            $item['children']=[];
        }
        api_return(200, '', ['treeData' => $list]);
    }

    /**
     * 数据列表
     * @param $p get请求参数
     * @return void
     */
    public static function tableList($p)
    {

        $params = [
            'where' => [],
            'page' => ($p['pageNo']) ?? 1,
            'pageSize' => ($p['pageSize']) ?? 10,
            'field' => '*',
            'with' => [
                'creator' => function ($query) {
                    $query->withField(['id', 'nickname'])->withDefault(['id' => '', 'nickname' => '管理员已删除']);
                },
                'children' => function ($query) {
                    $query->where('is_link','=',0)->withField(['*']);
                },
                'parentSku'=>function($query){
                    $query->withField(['id', 'label'])->withDefault(['id' => 0, 'label' => '无']);
    }
            ]
        ];

        if (!empty($p['parent_id'])) {
            $params['where'][] = ['parent_id', '=', $p['parent_id']];
        }
        if (!empty($p['sku_id']))
            $params['where'][] = ['sku_id', '=', $p['sku_id']];
        $list = BomModel::getList($params);
        $count = BomModel::count($params['where']);
        api_return(200, '', ['list' => $list, 'total' => $count]);
    }

    public static function edit($p)
    {

        $rule = [
            'sku_id' => 'require',
            'code' => 'require',
            'customer_id' => 'require',
            'production_date' => 'require',
            'weight' => 'require',
        ];

        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($p))
            api_return(500, $validate->getError());
        if (!empty($p['tempPath_file']) && !empty($p['fileType_file'])) {
            $p['file_path'] = self::getUploadField($p['tempPath_file'], $p['fileType_file'], $p['temp_old_file']);
        }
        if (!empty($p['tempPath']) && !empty($p['fileType'])) {
            $p['pic'] = self::getUploadField($p['tempPath'], $p['fileType'], $p['temp_old']);
        }
        if (empty($p['level']))
            $p['level'] = 0;
        Db::startTrans();
        $r1 = BomModel::editWithReturn($p);
        if ($r1) {
            foreach ($p['children'] as $item) {
                $item['parent_id'] = $r1->id;
                $item['creator_id'] = $p['creator_id'];
                $item['level'] = $p['level'] + 1;
                $item['parent_sku_id'] =$p['sku_id'];
                if (!empty($item['tempPath_file']) && !empty($item['fileType_file'])) {
                    $item['file_path'] = self::getUploadField($item['tempPath_file'], $item['fileType_file'], $item['temp_old_file']);
                }
                $r2 = BomModel::editWithReturn($item);
                if (!$r2) {
                    Db::rollback();
                    api_return(500, '异常回滚');
                }
            }
            Db::commit();
            api_return(200);
        } else {
            Db::rollback();
            api_return(500);
        }

    }

    public static function del($p)
    {
        $rule = ['ids' => 'require'];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($p))
            api_return(500, $validate->getError());
        $params = [
            'where' => [['id', 'in', $p['ids']]],
            'page' => 'all'
        ];
        $list = BomModel::getList($params);
        foreach ($list as $item) {
            if (!empty($item->stock))
                api_return(500, '当前分类库存尚余,请先删除库存分类');
            if (!empty($item->project_classify) && count($item->projectClassify)) {
                api_return(500, '当前分类项目尚余,请先清空项目分类', $list);
            }
        }
        BomModel::delByIds($p['ids']);

    }

    public static function files($p)
    {

        $params=[
            'where' => [],
            'page' => 'all',
            'field'=>'sku_id,top_id'
        ];

        if (!empty($p['parent_sku_id'])) {
            $params['where'][] = ['parent_sku_id', '=', $p['parent_sku_id']];

        }
        if (!empty($p['sku_id'])) {
            $params['where'][] = ['sku_id', '=', $p['sku_id']];
        }
        if (!$params['where']) {
            api_return(200, '暂无数据', ['list' => [], 'total' => 0]);
        }
        $dataList = BomModel::getList($params)->toArray();
        $skuList = array_unique(array_column($dataList, "sku_id"));
        $topIdList = array_unique(array_column($dataList,'top_id'));
        $params = [
            'where' => [
                ['sku_id','in',$skuList],
                ['top_id','in',$topIdList],
            ],
            'page' => 'all',
            'order' => 'id desc',
            'field' => 'sku_id,pic,weight,attribute_spec,id,parent_id,is_link,top_id',
            'with' => [
                'sku' => function ($query) {
                    return $query
                        ->withField(['id', 'code', 'pic_path', 'attribute_spec', 'label'])
                        ->withDefault(['code' => 'sku已删除', 'attribute_spec' => [], 'pic_path' => '', 'id' => '', 'label' => 'SKU已删除']);
                }
            ],
        ];
        $list = BomModel::getList($params)->toArray();
        $list = self::mergeBySkuId($list,$p['level'],$p['bom_id']);

        api_return(200, '', ['list' => $list, 'total' => 1]);
    }

    public static function getChildrenBySku($p)
    {

        if (!empty($p['parent_sku_id'])) {

            if(empty($p['bom_id'])){
                $where=[
                    ['sku_id','=',$p['parent_sku_id']],
                    ['parent_id','=',0]
                ];
                $parent_bom  = BomModel::where($where)->field('id, weight')->select()->toArray();
                $p['bom_id'] = implode(',',array_column( $parent_bom,'id'));
                $sumWeight = array_sum(array_column($parent_bom,'weight'));

            }else{
                $sumWeight = 0;
            }
            $params = [
                'where' => [
                    ['parent_sku_id','=',$p['parent_sku_id']],
                    ['parent_id','in',explode(',',$p['bom_id'])],
                ],
                'page' => 'all',
                'order' => 'id desc',
                'field' => 'sku_id,weight,id,parent_id,is_link',
                'with' => [
                    'sku' => function ($query) {
                        return $query
                            ->withField(['id' , 'label'])
                            ->withDefault(['id' => '', 'label' => 'SKU已删除']);
                    }
                ],
            ];
            $result = [];
            $list = BomModel::getList($params)->toArray();
            $index = 1;
            foreach ($list as $item) {
                $skuId = $item['sku_id'];
                if (!isset($result[$skuId])) {
                    $result[$skuId] = [
                        'sku_id' => $skuId,
                        'weight' => 0,
                        'sku' => $item['sku'],
                        'bom_id'=>[],
                        'index'=>$index,
                        'bom_weight'=>0,
                        'bom_weight_total'=>0,
                        'link_weight'=>0,
                    ];
                    $index++;
                }
                $result[$skuId]['bom_id'][]=$item['id'];
                //挂靠不计算
                if($item['is_link']==0) {
                    $result[$skuId]['bom_weight'] += $item['weight'];
                }else{
                    $result[$skuId]['link_weight'] += $item['weight'];
                }
                $result[$skuId]['bom_weight_total'] += $item['weight'];
                $result[$skuId]['bom_id'][]=$item['id'];
                $result[$skuId]['children'] =[];
                $result[$skuId]['id'] =$item['id'];
            }

            api_return(200, '', ['list' => array_values($result), 'sum_weight' => $sumWeight]);
        } else {
            api_return(200, '', ['list' => [], 'sum_weight' => 0]);
        }

    }

    public  static function mergeBySkuId($data,$level,$bom_id) {
        $result = [];

        foreach ($data as $item) {
            $skuId = $item['sku_id'];

            // 如果结果数组中还没有这个 sku_id，则初始化
            if (!isset($result[$skuId])) {
                $result[$skuId] = [
                    'id'=>$item['id'],
                    'sku_id' => $skuId,
                    'pic' => [],
//                    SKU全部重量
                    'weight' => 0,
                    'sku' => $item['sku'],
                    'spec_weight'=>[],
                    'bom_id'=>[],
//                    不计算挂靠重量
                    'bom_weight'=>0,
//                    挂靠+不挂靠重量
                    'bom_weight_total'=>0,
                    'link_weight'=>0,
                ];
            }
//            只计算上级bom的工单重量
            if(in_array($item['parent_id'],explode(',',$bom_id))){
                $result[$skuId]['bom_id'][]=$item['id'];
                //挂靠不计算
                if($item['is_link']==0) {
                    $result[$skuId]['bom_weight'] += $item['weight'];
                }else{
                    $result[$skuId]['link_weight'] += $item['weight'];
                }
                $result[$skuId]['bom_weight_total'] += $item['weight'];
                $result[$skuId]['id'] = $item['id'];
            }
            foreach ($item['attribute_spec'] as $spec){
                if($spec['input_type']==5) {
                    if (!isset($result[$skuId]['spec_weight'] [$spec['id']])) {
                        $result[$skuId]['spec_weight'] [$spec['id']] = ['name' => $spec['name'], 'weight' => $item['weight'] * (($spec['value']) ?? 0) / 100];
                    } else {
                        $result[$skuId]['spec_weight'] [$spec['id']]['weight'] += $item['weight'] * (($spec['value']) ?? 0) / 100;
                    }
                }
            }
            // 合并图片，确保不重复
            if ($item['pic']) {
                $result[$skuId]['pic'][] = $item['pic'];
            }
            // 累加SKU全部重量
            $result[$skuId]['weight'] += $item['weight'];
            $result[$skuId]['children'] =[];
            $result[$skuId]['percentage'] =100;
            $result[$skuId]['level'] =$level +1;
        }
        // 将结果数组的键重置为索引
        return array_values(($result));
    }

    public static function getChildrenBySkuTool($p)
    {

        if (!empty($p['parent_sku_id'])) {

            if(empty($p['bom_id'])){
                $where=[
                    ['sku_id','=',$p['parent_sku_id']],
                ];
                $parent_bom  = BomModel::where($where)->field('id, weight')->select()->toArray();
                $p['bom_id'] = implode(',',array_column( $parent_bom,'id'));
                $sumWeight = array_sum(array_column($parent_bom,'weight'));

            }else{
                $sumWeight = 0;
            }
            $params = [
                'where' => [
                    ['parent_sku_id','=',$p['parent_sku_id']],
                    ['parent_id','in',explode(',',$p['bom_id'])],
                ],
                'page' => 'all',
                'order' => 'id desc',
                'field' => 'sku_id,weight,id,parent_id,is_link',
                'with' => [
                    'sku' => function ($query) {
                        return $query
                            ->withField(['id' , 'label'])
                            ->withDefault(['id' => '', 'label' => 'SKU已删除']);
                    }
                ],
            ];
            $result = [];
            $list = BomModel::getList($params)->toArray();
            $index = 1;
            foreach ($list as $item) {
                $skuId = $item['sku_id'];
                if (!isset($result[$skuId])) {
                    $result[$skuId] = [
                        'sku_id' => $skuId,
                        'weight' => 0,
                        'sku' => $item['sku'],
                        'bom_id'=>[],
                        'index'=>$index,
                        'bom_weight'=>0,
                        'bom_weight_total'=>0,
                        'link_weight'=>0,
                    ];
                    $index++;
                }
                $result[$skuId]['bom_id'][]=$item['id'];
                //挂靠不计算
                if($item['is_link']==0) {
                    $result[$skuId]['bom_weight'] += $item['weight'];
                }else{
                    $result[$skuId]['link_weight'] += $item['weight'];
                }
                $result[$skuId]['bom_weight_total'] += $item['weight'];
                $result[$skuId]['bom_id'][]=$item['id'];
                $result[$skuId]['children'] =[];
                $result[$skuId]['id'] =$item['id'];
            }

            api_return(200, '', ['list' => array_values($result), 'sum_weight' => $sumWeight]);
        } else {
            api_return(200, '', ['list' => [], 'sum_weight' => 0]);
        }

    }

}
